import React, { Component } from 'react';
import _ from 'lodash';
import {
  StyleSheet, View, FlatList, DeviceEventEmitter,
} from 'react-native';
import produce from 'immer';
import TaskItem from './task-item';
import {
  ListFooter, BlankBackground, Loading,
} from '../../../components';
import * as inspectionService from '../../../services/inspection';
import theme from '../../../native-base-theme/variables/commonColor';

export default class TaskList extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  searchValue = '';

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: false,
    };
  }

  componentDidMount() {
    this._onInitRefresh();
    DeviceEventEmitter.addListener('refreshTaskPageEvent', this.refreshTaskPageEvent);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('refreshTaskPageEvent');
  }

  refreshTaskPageEvent = () => {
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await inspectionService.queryCheckTask({ page: currPage, isMyTask: this.props.title == 'mine', condition: '' });
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await inspectionService.queryCheckTask({ page: 1, isMyTask: this.props.title == 'mine', condition: '' });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await inspectionService.queryCheckTask({ page: 1, isMyTask: this.props.title == 'mine', condition: '' });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ condition: this.searchValue });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ condition: this.searchValue });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ condition: this.searchValue });
    }
  }

  _onItemClick = (item) => {
    alert('@');
  }

  _renderItem = (item) => (<TaskItem item={item.item} onItemClick={this._onItemClick} />);

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 0.5, backgroundColor: 'gray' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  render() {
    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            renderItem={this._renderItem}
            data={list}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
          />
        );
      }
    }

    return (
      <View style={{ flex: 1, backgroundColor: theme.myPrimary, marginTop: 48, marginBottom: 49 }}>
        {mView}
      </View>
    );
  }
}
